package com.situ.ymall.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.ymall.admin.entity.Goods;
import com.situ.ymall.admin.entity.GoodsPicture;
import com.situ.ymall.admin.mapper.GoodsMapper;
import com.situ.ymall.admin.mapper.GoodsPictureMapper;
import com.situ.ymall.admin.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
   @Autowired
    private GoodsMapper goodsMapper;
   @Autowired
   private GoodsPictureMapper goodsPictureMapper;

    @Override
    public Goods remove(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        goods.setStatus(1);
        goodsMapper.updateByPrimaryKey(goods);
        return goods;
    }

    @Override
    public Goods insert(Goods good) {
        good.setStatus(0);

        goodsMapper.insert(good);
        if(good.getPictures() != null && good.getPictures().size() > 0){
            goodsPictureMapper.batchInsert(good);
        }
        return good;
    }

    @Override
    @Transactional
    public Goods update(Goods good) {
        //保存商品
        goodsMapper.updateByPrimaryKey(good);
        //保存图片
        // 1.删除原有图片
        goodsPictureMapper.deleteByGoodsId(good.getId());
        // 2.添加新的图片
        if(good.getPictures() != null && good.getPictures().size() > 0){
            goodsPictureMapper.batchInsert(good);
        }
        Goods goods = goodsMapper.selectByPrimaryKey(good.getId());
        return goods;
    }

    @Override
    public PageInfo selectByPage(Integer page, Integer limit, Goods goods) {
        if(page == null) page = 1;
        if (limit == null){
            List list = goodsMapper.select(goods);
            limit = list.size();
        }
        PageHelper.startPage(page,limit);
        List list = goodsMapper.select(goods);
        PageInfo pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Goods recover(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        goods.setStatus(0);
        goodsMapper.updateByPrimaryKey(goods);
        return goods;
    }
}
